<template>
  <q-scroll-area ref="scrollTargetRef" :thumb-style="thumbStyle">
    <q-infinite-scroll :offset="250" :scroll-target="$refs.scrollTargetRef"  ref="scrollTarget">
      <div class="row flex">
        <div class="col-lg-3 col-md-6" v-for="(item, index) in cardInfo" :key="item.boxId+index">
          <div class="card-container">
            <div class="card-left">
              <div class="id">{{ item.prodId }}</div>
              <div class="content">
                <div class="no-wrap">
                  最后部署时间: {{ dateToDay(item.deployedDate) }}
                </div>
                <div class="no-wrap">
                  关联设备: {{ item.assetNums }}
                </div>
                <div class="no-wrap flex items-center">
                  连接状态<span> <q-icon name="iconfont icontubiao-72" class="text-grey" style="margin-right: 5px;margin-left: 2px;margin-top: -1px;font-size: 14px" />
                  <q-tooltip max-width="300px">网关和UCLOUD平台的连接状态</q-tooltip></span>:{{ item.connectStatus ? connectStatusObj[item.connectStatus] : '--'}}
                </div>
                <div class="no-wrap">
                  部署状态<span><q-icon name="iconfont icontubiao-72" class="text-grey" style="margin-right: 5px;margin-left: 2px;margin-top: -1px;font-size: 14px" />
                  <q-tooltip max-width="300px">UCLOUD平台的部署状态</q-tooltip></span>:{{ item.deploymentStatus ? (deploymentStatusObj[item.deploymentStatus] || '--') : '--'  }}
                </div>
                <div class="no-wrap">
                  关联类型: {{ item.isPlc === 1 ? 'PLC': 'CNC' }}
                </div>
                <div class="no-wrap">
                  最后上线时间: {{ dateToDay(item.lastOnlineTime) }}
                </div>
              </div>
            </div>
            <div class="card-right">
              <div style="display: flex;align-items: center;line-height: 1">
<!--                <Signal :value="4"/>-->
                <div class="living">
                  <div class="status" :class="{'off': item.onLineStatus !== 'ONLINE'}"></div>
                  {{item.onLineStatus === 'ONLINE' ? '在线':'离线'}}
                </div>
                <div class="type">
                  <span>{{ item.wanCfg ? item.wanCfg.toUpperCase() : '' }}</span>
                </div>
              </div>
<!--                <div class="warning">-->
<!--                  <q-icon class="iconfont icontubiao2-91 margin-r-10"></q-icon>-->
<!--                  <q-icon class="iconfont icontubiao2-92"></q-icon>-->
<!--                </div>-->
            </div>
            <div class="operate">
              <q-icon class="iconfont icontubiao-28 margin-r-10 detail" @click="goDetail(item)"></q-icon>
              <q-icon class="iconfont icontubiao-16 delete" @click="deleteData(item)"></q-icon>
            </div>
          </div>
        </div>
      </div>
    </q-infinite-scroll>
  </q-scroll-area>
</template>

<script>
// import Signal from './signal'
import { deleteBox } from '../../../../boot/miot/list'
import { deletePlcBox } from '../../../../boot/miot/plc-list'
import { mapGetters } from 'vuex'
import moment from 'moment'
import { deploymentStatusObj } from './plc-dialog/constant'

export default {
  name: 'list-card',
  components: {
    // Signal
  },
  props: {
    cardInfo: {
      type: Array,
      default: () => []
    },
    connectStatusObj: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      // 滚动条样式
      thumbStyle: this.CommonConfig.thumbStyle,
      deploymentStatusObj: deploymentStatusObj
    }
  },
  computed: {
    ...mapGetters([
      'client'
    ])
  },
  methods: {
    /**
     * 跳转到详情页面
     */
    goDetail (info) {
      const isPlc = info.isPlc === 1
      const isOldCnc = info.isPlc !== 1 && !info.connectStatus
      // 如果不在线的话 就不能跳转了
      if (isOldCnc) {
        if (info.onLineStatus !== 'ONLINE') {
          this.$message.warning('设备已离线，请检查网关网络')
          return
        }
        this.$router.push({
          name: 'miotDetail',
          query: {
            boxId: info.boxId,
            deployedDate: info.deployedDate,
            boxStatus: info.boxStatus,
            wanCfg: info.wanCfg ? info.wanCfg.toUpperCase() : '',
            onLineStatus: info.onLineStatus,
            _time: new Date().getTime()
          }
        })
      } else {
        const deviceId = info.deviceInfo?.map(item => item.id) || []
        this.$router.push({
          name: 'plcDetail',
          query: {
            boxId: info.ucloudBoxId,
            productId: info.productId,
            deployedDate: this.dateToDay(info.deployedDate),
            boxNum: info.boxId,
            deviceId: deviceId?.length > 0 ? JSON.stringify(deviceId) : '',
            moduleType: isPlc ? 0 : 1,
            _time: new Date().getTime()
          }
        })
      }
    },

    /**
     * 弹框提示是否删除
     */
    deleteData (info) {
      const isPlc = info.isPlc === 1
      const isOldCnc = info.isPlc !== 1 && !info.connectStatus
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确认要删除此网关信息吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        if (isPlc) {
          this.deletePlcDataConfirm(info.boxId, 0, info.ucloudBoxId)
        } else {
          if (isOldCnc) {
            this.deleteDataConfirm(info.boxId)
          } else {
            this.deletePlcDataConfirm(info.boxId, 1, info.ucloudBoxId)
          }
        }
      })
    },

    /**
     * 执行删除操作
     */
    async deleteDataConfirm (boxId) {
      if (!boxId) return
      const data = await deleteBox(boxId)
      if (data.success) {
        this.$emit('deleteSuccess')
      } else {
        this.$message.error('删除失败')
      }
    },

    /**
     * 执行删除操作
     */
    async deletePlcDataConfirm (boxId, modelType = 0, ucloudBoxId) {
      if (!boxId) return
      await deletePlcBox(boxId, modelType, ucloudBoxId)
      this.$emit('deleteSuccess')
    },

    /**
     * 通过部署时间，计算运行时间
     * @param date
     */
    dateToDay (date) {
      if (!date) return '---'
      if (isNaN(Number(date))) {
        return moment(date).format('YYYY-MM-DD HH:mm:ss')
      }
      return moment(Number(date)).format('YYYY-MM-DD HH:mm:ss')
    },

    /**
     * 检查盒子是否部署成功
     */
    checkSuccess (boxId) {
      return new Promise((resolve, reject) => {
        if (this.client && this.client.connected) {
          const subscribe = this.client.subscribe(
            `/topic/deploy/newBox/${boxId}`,
            (message) => {
              try {
                subscribe.unsubscribe()
                const ret = JSON.parse(message.body)
                if (ret && ret.data && ret.data.status === 'success') {
                  resolve()
                } else {
                  reject()
                }
              } catch (e) {
                console.log('解析socket内存报警错误' + e)
                reject()
              }
            }
          )
        } else {
          this.$message.warning('websocket断开连接啦~请稍后重试')
          reject()
        }
      })
    }
  }
}
</script>

<style scoped lang="stylus">
.no-wrap
  white-space nowrap
  text-overflow ellipsis
  overflow hidden
.card-container
  height 187px
  cursor pointer
  background rgba(255,255,255,1)
  box-shadow 0 0 4px 0 rgba(22,22,22,0.2)
  border-radius 6px
  margin  10px
  padding 0 10px
  display flex
  justify-content space-between
  position relative

  .card-left
    margin 16px 0
    max-width 65%
    .id
      color #333333
      font-weight 500
      font-size 16px
      white-space nowrap
      text-overflow ellipsis
      overflow hidden
    .content
      margin-top 15px
      display flex
      flex-direction column
      line-height 1.5
      .gateway-status
        color $positive
      .exception
        color $warning
  .card-right
    margin-top 12px
    .living
      text-align right
      margin-left 10px
      margin-right 8px
      position relative
      width 43px
      .status
        width 10px
        height 10px
        border-radius 50%
        background $positive
        position absolute
        left 0
        top 2px
      .off
        background #666666
    .warning
      margin-top 9px
      color $negative
      text-align right
  .operate
    display flex
    justify-content space-around
    transition height 300ms ease-in-out
    align-items center
    height 0
    overflow hidden
    width 100%
    background #ffffff
    border-radius 6px
    position absolute
    bottom 0
    left 0
    .detail
      width 50%
      text-align center
      color $primary
    .delete
      width 50%
      color $negative
      text-align center
.card-container:hover
  background #DFE4FF
.card-container:hover .operate
  height 48px
</style>
